<template>
  <div class="supplyDrawer">
    <Drawer title="供应信息导入预览" placement="right" v-model="showValue" @on-visible-change="onVisibleChange"
      closable width="90">
      <div class="fd">
        <Button class="mr_24 mb_20" type="success" v-permission="20" @click="onSubmit()"
          size="large">提交</Button>
      </div>
      <div class="bd">
        <Form ref="formValidate" :model="formValidate">
          <Table ref="table" border :columns="columns" height="700" :data="formValidate.tableData">
            <!-- 商品编码 -->
            <template slot="raiseCode" slot-scope="{ index, row }">
              <div v-if="row.isEdit">{{ row.raiseCode }}</div>
              <FormItem v-else :prop="'tableData.' + index + '.raiseCode'" :rules="{
                  required: false,
                  message: '请输入商品编码',
                  trigger: 'change',
                }">
                <Input v-model="formValidate.tableData[index].raiseCode" :border="false" clearable
                  maxlength="20" placeholder="请输入商品编码"></Input>
              </FormItem>
            </template>
            <!-- 商品名称 --->
            <template slot="materialName" slot-scope="{ index, row }">
              <div v-if="row.isEdit">{{ row.materialName }}</div>
              <FormItem v-else :prop="'tableData.' + index + '.materialName'" :rules="{
                  required: true,
                  message: '请输入商品名称',
                  trigger: 'change',
                }">
                <Input v-model="formValidate.tableData[index].materialName" :border="false"
                  clearable maxlength="20" placeholder="请输入商品名称"></Input>
              </FormItem>
            </template>
            <!-- 商品分类 -->
            <template slot="productCategoryName" slot-scope="{ index, row }">
              <div v-if="row.isEdit">{{ row.productCategoryName }}</div>
              <FormItem v-else :prop="'tableData.' + index + '.productCategoryId'" :rules="{
                  type: 'number',
                  required: true,
                  message: '请选择商品分类',
                  trigger: 'change',
                }">
                <Select v-model="formValidate.tableData[index].productCategoryId"
                  placeholder="请选择商品分类" filterable transfer>
                  <Option :value="item.id" v-for="(item, index) in materialClassTree" :key="index">
                    {{ item.categoryName }}</Option>
                </Select>
              </FormItem>
            </template>
            <!-- 食物分类 -->
            <template slot="localFoodTypeName" slot-scope="{ index, row }">
              <div v-if="row.isEdit">{{ row.localFoodTypeName }}</div>
              <FormItem v-else :prop="'tableData.' + index + '.localFoodTypeId'" :rules="{
                  type: 'number',
                  required: true,
                  message: '请选择食物分类',
                  trigger: 'change',
                }">
                <Select v-model="formValidate.tableData[index].localFoodTypeId"
                  placeholder="请选择食物分类" filterable transfer>
                  <Option :value="item.id" v-for="(item, index) in materialTypeList" :key="index">
                    {{ item.name }}</Option>
                </Select>
              </FormItem>
            </template>
            <!-- 计量单位 -->
            <template slot="specificationValue" slot-scope="{ index, row }">
              <div v-if="row.isEdit">{{ row.specification }}</div>
              <FormItem v-else :prop="'tableData.' + index + '.specificationValue'" :rules="{
                  type: 'number',
                  required: true,
                  message: '请选择计量单位',
                  trigger: 'change',
                }">
                <Select v-model="formValidate.tableData[index].specificationValue"
                  placeholder="请选择计量单位" filterable transfer @on-change="onChangeUnit(index, row)">
                  <Option :value="item.specificationValue"
                    v-for="(item, index) in specificationList" :key="index">{{ item.specification }}
                  </Option>
                </Select>
              </FormItem>
            </template>
            <!-- 单位重量 -->
            <template slot="unitWeight" slot-scope="{ index, row }">
              <div v-if="row.isEdit">{{ row.unitWeight }}</div>
              <FormItem v-else :prop="'tableData.' + index + '.unitWeight'" :rules="{
                  type: 'number',
                  required: true,
                  min: 0.01,
                  message: '请选择单位重量',
                  trigger: 'change',
                }">
                <!-- :disabled="[0,1].includes(formValidate.tableData[index].specificationValue)" -->
                <Input v-model.number="formValidate.tableData[index].unitWeight" :border="false"
                  clearable maxlength="20" placeholder="请输入单位重量"></Input>
              </FormItem>
            </template>
            <!-- 单价 -->
            <template slot="price" slot-scope="{ index, row }">
              <div v-if="row.isEdit">{{ row.price }}</div>
              <FormItem v-else :prop="'tableData.' + index + '.price'" :rules="{
                  type: 'number',
                  required: true,
                  min: 0.01,
                  message: '请输入单价',
                  trigger: 'change',
                }">
                <Input v-model.number="formValidate.tableData[index].price" :border="false"
                  clearable maxlength="20" placeholder="请输入单价"></Input>
              </FormItem>
            </template>
            <!-- 是否称重出入库 -->
            <template slot="weightFlag" slot-scope="{ index, row }">
              <div v-if="row.isEdit">
                {{
                  row.weightFlag == 0 ? "否" : row.weightFlag == 1 ? "是" : ""
                }}
              </div>
              <FormItem v-else :prop="'tableData.' + index + '.weightFlag'" :rules="{
                  type: 'number',
                  required: false,
                  message: '请选择是否称重出入库',
                  trigger: 'change',
                }">
                <Select v-model.number="formValidate.tableData[index].weightFlag"
                  placeholder="请选择是否称重出入库" filterable transfer>
                  <Option :value="0">否</Option>
                  <Option :value="1">是</Option>
                </Select>
              </FormItem>
            </template>
            <!-- 商品码 -->
            <template slot="snCode" slot-scope="{ index, row }">
              <div v-if="row.isEdit">{{ row.snCode }}</div>
              <FormItem v-else :prop="'tableData.' + index + '.snCode'" :rules="{
                  required: false,
                  message: '请输入商品码',
                  trigger: 'change',
                }">
                <Input v-model="formValidate.tableData[index].snCode" :border="false" clearable
                  maxlength="20" placeholder="请输入商品码"></Input>
              </FormItem>
            </template>
            <!-- 品牌 -->
            <template slot="brand" slot-scope="{ index, row }">
              <div v-if="row.isEdit">{{ row.brand }}</div>
              <FormItem v-else :prop="'tableData.' + index + '.brand'" :rules="{
                  required: false,
                  message: '请输入品牌',
                  trigger: 'change',
                }">
                <Input v-model="formValidate.tableData[index].brand" :border="false" clearable
                  maxlength="20" placeholder="请输入品牌"></Input>
              </FormItem>
            </template>
            <!--生效日期-->
            <template slot="effectiveDate" slot-scope="{ index, row }">
              <div v-if="row.isEdit">{{ row.effectiveDate }}</div>
              <FormItem v-else :prop="'tableData.' + index + '.effectiveDate'"
                :rules="{ required: false, message: '请输入生效日期', trigger: 'change' }">
                <DatePicker :value="formValidate.tableData[index].effectiveDate"
                  @on-change="onChange($event, index)" :options="options" format="yyyy-MM-dd"
                  transfer placeholder="请输入日期" />
              </FormItem>
            </template>
            <template slot="operation" slot-scope="{ index, row }">
              <div class="flex">
                <Button type="primary" size="small" v-if="row.isEdit == true" v-permission="30"
                  @click="onEdit(index, row,true)" style="margin-right: 6px">
                  编辑
                </Button>
                <Button v-if="row.isEdit == false" size="small" v-permission="30"
                  @click="onSave(index, row)"
                  style="margin-right: 6px; background: #19be6b; color: #ffffff">
                  保存
                </Button>
                <Button v-if="row.isEdit == false" type="warning" size="small" v-permission="30"
                  @click="onEdit(index, row,false)" style="margin-right: 6px">
                  取消
                </Button>
                <Button type="error" size="small" v-permission="40" :style="{ padding: '0 8px' }"
                  @click="onDelete(row)">
                  删除
                </Button>
              </div>
            </template>
          </Table>
          <div class="mt_10 flex" :style="{ color: errorCount > 0 ? '#cc0000' : '#19be6b' }">
            <div v-if="errorCount > 0">
              <Icon type="ios-information-circle-outline" size="17" color="red" />&nbsp;当前预览数据存在
              {{
                errorCount
              }}
              条错误数据，请全部修正后点击提交按钮提交为正式数据。
            </div>
            <div v-else>
              <Icon type="md-checkmark-circle" size="17" color="green" />
              &nbsp;当前预览数据全部正确，请点击提交按钮提交为正式数据。
            </div>
          </div>
        </Form>
        <div class="cus_page">
          <cus-page :data="pages" simple class="mt_10" @pageChange="postFoodRaiseApi"></cus-page>
        </div>
      </div>
    </Drawer>
    <!-- 错误提示 -->
    <excelErrorModal ref="excelErrorModal"></excelErrorModal>
  </div>
</template>

<script>
import {
	postFoodRaise,
	getProductCategoryList,
	localfoodtype,
	selectBasSpecificationList,
	saveFoodRaise,
	deleteFoodRaise,
	submitFoodRaise
} from '@/api/organ/dishesModule'
import excelErrorModal from './excelErrorModal.vue'

export default {
	components: { excelErrorModal },
	name: 'supplyDrawer',
	data() {
		return {
			showValue: false,
			options: {
				disabledDate(date) {
					return date && date.valueOf() < Date.now() - 86400000
				}
			},
			materialClassTree: [], // 商品种类
			materialTypeList: [], // 食材种类
			specificationList: [], // 计量单位
			isEdit: true, // 编辑保存标识
			kitchenArea: '', // 区域
			errorCount: null, // 总计数据错误数量
			formValidate: {
				tableData: []
			},
			columns: [
				{
					key: 'errReason',
					align: 'center',
					width: 212,
					renderHeader: (h, params) => {
						return h('div', [
							h('a', {
								style: {
									color: '#cc0000'
								},
								domProps: {
									innerHTML: '错误信息'
								}
							})
						])
					},
					render: (h, params) => {
						return h('div', [
							h(
								'span',
								{
									style: { color: '#cc0000', padding: '5px' }
								},
								params.row.errReason
							)
						])
					}
				},
				{
					title: '商品编码',
					slot: 'raiseCode',
					align: 'center',
					minWidth: 100
					// renderHeader: (h, params) => {
					//   return h("div", [
					//     h("a", {
					//       style: {
					//         // color: "#cc0000",
					//       },
					//       domProps: {
					//         innerHTML: "商品编码",
					//       },
					//     }),
					//   ]);
					// },
				},
				{
					title: '商品名称',
					slot: 'materialName',
					align: 'center',
					minWidth: 130,
					renderHeader: (h, params) => {
						return h('div', [
							h('a', {
								style: {
									color: '#cc0000'
								},
								domProps: {
									innerHTML: '* 商品名称'
								}
							})
						])
					}
				},
				{
					title: '商品分类',
					slot: 'productCategoryName',
					align: 'center',
					minWidth: 120,
					renderHeader: (h, params) => {
						return h('div', [
							h('a', {
								style: {
									color: '#cc0000',
									border: 'none !important'
								},
								domProps: {
									innerHTML: '* 商品分类'
								}
							})
						])
					}
				},
				{
					title: '食物分类',
					slot: 'localFoodTypeName',
					align: 'center',
					minWidth: 120,
					renderHeader: (h, params) => {
						return h('div', [
							h('a', {
								style: {
									color: '#cc0000'
								},
								domProps: {
									innerHTML: '* 食物分类'
								}
							})
						])
					}
				},
				{
					title: '计量单位',
					slot: 'specificationValue',
					align: 'center',
					minWidth: 120,
					renderHeader: (h, params) => {
						return h('div', [
							h('a', {
								style: {
									color: '#cc0000'
								},
								domProps: {
									innerHTML: '* 计量单位'
								}
							})
						])
					}
				},
				{
					title: '单位重量',
					slot: 'unitWeight',
					align: 'center',
					minWidth: 130,
					renderHeader: (h, params) => {
						return h('div', [
							h('a', {
								style: {
									color: '#cc0000'
								},
								domProps: {
									innerHTML: '* 单位重量(KG)'
								}
							})
						])
					}
				},
				{
					title: '单价',
					slot: 'price',
					align: 'center',
					minWidth: 100,
					renderHeader: (h, params) => {
						return h('div', [
							h('a', {
								style: {
									color: '#cc0000'
								},
								domProps: {
									innerHTML: '* 单价(元)'
								}
							})
						])
					}
				},
				{
					title: '是否称重入库',
					slot: 'weightFlag',
					align: 'center',
					minWidth: 130
				},
				{
					title: '商品码',
					slot: 'snCode',
					align: 'center',
					minWidth: 100
				},
				{
					title: '品牌',
					slot: 'brand',
					align: 'center',
					width: 130
				},
				{
					title: '生效日期',
					slot: 'effectiveDate',
					align: 'center',
					width: 130
				},
				{
					title: '操作',
					width: 150,
					fixed: 'right',
					slot: 'operation',
					align: 'center'
				}
			],
			pages: {
				page: 1,
				pageSize: 10,
				pageTotal: 0
			},		
		}
	},
	mounted() {},
	props: {},
	methods: {
		onVisibleChange(v) {
			if (!v) this.pages.page = 1
		},
		show(data) {
			this.isEdit = true
			this.kitchenArea = this.$cu.deepClone(data.data.kitchenArea)
			this.showValue = true
			this.getProductCategoryListApi()
			this.localfoodtypeApi()
			this.selectBasSpecificationListApi()
			this.postFoodRaiseApi()
		},
		onSubmit() {
			this.submitFoodRaiseApi()
		},
		onEdit(index, row, flag) {
			// 如果是取消的话编辑限制打开
			this.isEdit = flag ? this.isEdit : true
			console.log(this.isEdit, false)
			if (this.isEdit) {
				// 取消为false,isEdit为true编辑限制打开,编辑为true,isEdit为flase编辑限制关闭
				this.isEdit = !flag
				this.$set(
					this.formValidate.tableData[index],
					'isEdit',
					!this.formValidate.tableData[index].isEdit
				)
			} else {
				this.$Message.warning('你有一条正在编辑的供应信息')
			}
		},
		onSave(index, row) {
			this.$refs['formValidate'].validate((valid) => {
				if (valid) {
					this.isEdit = true
					console.log('数据已修改完')
					this.saveFoodRaiseApi(index)
				} else {
					console.log('非验证')
				}
			})
		},
		onDelete(row) {
			this.$cu.dialog({ params: row }).then(({ id }) => {
				this.deleteFoodRaiseApi(id)
			})
		},
		onChange(date, index) {
			this.$set(this.formValidate.tableData[index], 'effectiveDate', date)
			console.log(date, index)
		},
		//
		onChangeUnit(index, row) {
			console.log(this.formValidate.tableData[index].specificationValue, index)
			if (this.formValidate.tableData[index].specificationValue == 0) {
				this.formValidate.tableData[index].unitWeight = 1
			} else if (this.formValidate.tableData[index].specificationValue == 1) {
				this.formValidate.tableData[index].unitWeight = 0.5
			}
		},
		// 列表
		postFoodRaiseApi() {
			return new Promise((resolve) => {
				let params = {
					kitchenArea: this.kitchenArea,
					currentPage: this.pages.page,
					pageSize: this.pages.pageSize
				}
				postFoodRaise(params).then((res) => {
					if (res.code === 1) {
						res.data.list.forEach((element) => {
							element.isEdit = true
						})
						this.formValidate.tableData = res.data.list
						this.errorCount = res.data.extra.errorCount
						this.pages.pageTotal = res.data.total
						resolve()
					}
				})
			})
		},
		// 食材分类-----------------接口
		localfoodtypeApi() {
			return new Promise((resolve) => {
				localfoodtype({}).then((res) => {
					if (res.code === 1) {
						this.materialTypeList = res.data
						resolve()
					}
				})
			})
		},
		// 获取食材规格
		selectBasSpecificationListApi() {
			return new Promise((resolve) => {
				selectBasSpecificationList({}).then((res) => {
					if (res.code === 1) {
						this.specificationList = res.data
						console.log(res.data)
						resolve()
					}
				})
			})
		},
		// 商品分类
		getProductCategoryListApi() {
			return new Promise((resolve) => {
				getProductCategoryList().then((res) => {
					if (res.code == 1) {
						this.materialClassTree = res.data
						resolve()
					}
				})
			})
		},
		// 保存
		saveFoodRaiseApi(index) {
			return new Promise((resolve) => {
				let params = this.formValidate.tableData[index]
				saveFoodRaise(params).then((res) => {
					if (res.code == 1) {
						this.postFoodRaiseApi()
						resolve()
					}
				})
			})
		},
		// 删除
		deleteFoodRaiseApi(id) {
			return new Promise((resolve) => {
				deleteFoodRaise({ id: id }).then((res) => {
					if (res.code == 1) {
						this.postFoodRaiseApi()
						resolve()
					}
				})
			})
		},
		// 提交
		submitFoodRaiseApi() {
			return new Promise((resolve) => {
				let params = {
					kitchenArea: this.kitchenArea
				}
				submitFoodRaise(params).then((res) => {
					if (res.code == 2888) {
						this.$refs['excelErrorModal'].data = res.data
						this.$refs['excelErrorModal'].show()
						resolve()
					}
					if (res.code == 1) {
						// this.$refs['excelErrorModal'].isEdit = false;
						// this.$refs['excelErrorModal'].show();
						this.$Message.success('导入成功!')
						// this.$router.push(
						//   "/view/baseManage/localfoodModule/supplyInformationManage"
						// );
						this.$emit('onOk', res)
						this.showValue = false
					}
				})
			})
		}
	}
}
</script>

<style scoped>
/deep/.ivu-form-item-error-tip {
	display: none;
}
/deep/.ivu-input {
	height: 48px !important;
}
/deep/.ivu-table-cell {
	padding: 0;
}
/deep/.ivu-form-item {
	margin-bottom: 0;
}
/deep/ .ivu-select-selection {
	/* border: 1px solid blue; */
	height: 48px !important;
	line-height: 48px !important;
}
/deep/#html .ivu-input,
#html .ivu-select-single,
#html .ivu-select-selection {
	height: 48px !important;
	line-height: 48px !important;
}
.fd {
	display: flex;
	/* justify-content: flex-end; */
}
.bd {
	border: 1px solid #e3e8ee;
	border-radius: 8px;
	padding: 10px;
}
</style>
